<template>

  <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
    <template v-for="dateStr in dates" :key="dateStr">
      <van-divider content-position="left">{{ formatDate(dateStr) }}</van-divider>
      <article class="article" v-for="story in storiesByDate[dateStr]" :key="story.id" @click="gotoArticle(story.id)">
        <div class="left">
          <div class="title">{{ story.title }}</div>
          <div class="hint">{{ story.hint }}</div>
        </div>
        <div class="right">
          <img :src="story.images[0]" :alt="story.title">
        </div>
      </article>
    </template>
  </van-list>


</template>


<script setup>
import { getHistoryDailyList } from '@/api/index.js'
import { formatDate } from "@/tools/index.js"
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()


const props = defineProps({
  currentDateTime: {
    type: String,
  },
})

const currentDateTime = computed(() => props.currentDateTime)
const prevDate = ref('')


const loading = ref(false)
const finished = ref(false)

const storiesByDate = ref({}) // 按日期分组的stories { '20231010': [...], '20231009': [...] }
const dates = ref([]) // 存储日期顺序 ['20231010', '20231009']


onMounted(async () => {
  loading.value = true;
  const response = await getHistoryDailyList(currentDateTime.value);
  prevDate.value = response.date; //前一天日期
  storiesByDate.value[response.date] = response.stories
  dates.value.push(response.date)
  loading.value = false;
});

const onLoad = async () => {

  loading.value = true;
  const response = await getHistoryDailyList(prevDate.value);
  if (response.stories.length === 0) {
    finished.value = true;
    return;
  }
  if (response.stories && response.stories.length > 0) {
    prevDate.value = response.date; //前一天日期
    storiesByDate.value[response.date] = response.stories
    dates.value.push(response.date)
  }
  loading.value = false;
};

const gotoArticle = (id) => {

  router.push({ path: `/article/${id}` })

};



</script>

<style scoped>
:deep(.van-divider) {
  padding-left: 15px;
}

:deep(.van-divider:before) {
  content: none;
}

.article {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  cursor: pointer;
}


.left {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  flex-direction: column;
  width: 70%
}

.title {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.hint {
  font-size: 14px;
  color: #999;
}



.right {
  width: 80px;
  height: 80px;
  overflow: hidden;
  object-fit: cover;
}

.right img {
  width: 100%;

}
</style>
